package baza_mysql;

//import java.sql.Connection;
import com.mysql.jdbc.Connection;

import com.mysql.jdbc.Statement;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oo.rejestracja;

public class Connect_MySQL {

	private Connection con=null;
	public Connect_MySQL(){
		try{
		  Class.forName("com.mysql.jdbc.Driver");
	      //lokalnie
	      con =  (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/szkola","root", "");
	      //na eatj
	      //con =  (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3307/mateusz1980?autoReconnect=true");
		}
		catch(Exception e){
			System.out.println("blad konstruktor"+e.getMessage());
		}
	}
	public Connection getCon() {
		return con;
	}

	public void setCon(Connection con) {
		this.con = con;
	}
	private int get_all_users(rejestracja rej){
		try {	      
		       Statement st=(Statement) con.createStatement();
		       ResultSet rs=st.executeQuery("select * from user");
		       while(rs.next()){
		    	   if(rej.getEmail().equals(rs.getString("email")))
		    		   return 1;
		       }
		       return 0;
		}
		catch(SQLException e) {
			System.out.println("koniec"+e.getMessage());
			return -1;
		}
	}
	public int add_new_user(rejestracja rej) throws ClassNotFoundException{
		try {	      
			   switch(get_all_users(rej))
			   {
			   case 0:
				   //dodawanie usera
				   PreparedStatement s;
				   s = con.prepareStatement ("INSERT INTO user (nazwa,haslo,email) VALUES(?,?,?)");
				   s.setString (1, rej.getName());
				   s.setString (2, rej.getHaslo());
				   s.setString (3, rej.getEmail());
				   //int count = 
				   s.execute();//.executeUpdate();
				   s.close ();
				   return 0;
			   case 1:
				   //user jest w bazie
				   System.out.println("user juz jest");
				   return 1;
			   case -1:
				   //blad !!!!!
				   return -1;
			   }
		      return -1;
		}
		catch(SQLException e) {
			System.out.println("koniec"+e.getMessage());
			return -1;
		}
		
		    }

	
}
